<template>
	<view class="echarts" :id="options.id" :prop="options" @click="echarts.onClick" :change:prop="echarts.update">
	</view>
</template>

<script>
	export default {
		name: 'Echarts',
		props: {
			options: {
				type: Object,
				default: () => {}
			},
		},
		created() {
			// 设置随机数id
			let t = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
			let len = t.length
			let id = ''
			for (let i = 0; i < 32; i++) {
				id += t.charAt(Math.floor(Math.random() * len))
			}
			this.options.id = id
		},
		methods: {
			onViewClick(options) {
				// console.log(options)
			}
		}
	}
</script>

<script module="echarts" lang="renderjs">
	import echarts from '@/static/js/echarts.min.js'
	import config from './echarts.config.js'
	
	export default {
		data() {
			return {
				chart: null,
			}
		},
		mounted() {
			this.init()
		},
		methods: {
			init() {
				this.chart = echarts.init(document.getElementById(this.options.id));
				this.chart.setOption(this.options);
			},
			update(newValue, oldValue, ownerInstance, instance) {
				try {
					this.showLoading();
					let length = this.recursionObj(newValue)
					if (!length) {
						this.chart.hideLoading();
						this.initInnerHTML()
					} else {
						setTimeout(() => {
							this.chart.hideLoading();
							this.chart.setOption(newValue,true);
						}, 500);
					}
				} catch(e) {}
			},
			onClick(event, ownerInstance) {
				// 调用 service 层的方法
				ownerInstance.callMethod('onViewClick', {
					test: 'test'
				})
			},
			/**
			 * 添加formatter方法
			 * @param {Object} obj
			 */
			recursionObj(obj) {
				let flag = false;
				for (var i in obj) {
					if(i == 'series') {
						if(Object.prototype.toString.call(obj[i]) === "[object Object]" && Object.keys(obj[i]).length) {
							flag = true;
						} else if(Object.prototype.toString.call(obj[i]) === "[object Array]" && obj[i].length) {
							let f = false;
							for(let y=0;y < obj[i].length;y++) {
								obj[i][y].data.length ? f = true : "";
							}
							flag = f;
						}
					}
					if (typeof obj[i] === "object") {
						this.recursionObj(obj[i]);
					} else {
						for (let key in config) {
							if (i == 'format' && obj[i] == key) {
								obj['formatter'] = config[key]
							}
						}
					}
				}
				return flag
			},
			/**
			 * 显示加载动画
			 */
			showLoading() {
				this.chart.showLoading({
					text: 'loading',
					color: '#c23531',
					textColor: '#000',
					maskColor: 'rgba(255, 255, 255, 0.2)',
				});
			},
			/**
			 * 空数据展示
			 */
			initInnerHTML() {
				var option = {
					title: {
						textStyle: {
							color: '#ccc',
							fontSize: 18
						},
						text: "暂无数据",
						left: "center",
						top: "center"
					}
				}
				this.chart.setOption(option,true);
			}
		}
	}
</script>

<style>
	.echarts {
		width: 100%;
		height: 100%;
	}
</style>
